﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using Core;
using static SqlSugarAndEntity.Extension.DataModel;
using SqlSugarAndEntity.Base;
using SqlSugarAndEntity.Extension;
using SqlSugarAndEntity.Entity;
using Repository.Base;
using Core.AutoFacService.Attributes.InjectAttributes;

namespace Repository.Dictionary
{
    [Inject]
    public class DictionaryRepository : BaseRepository<sys_dictionary>, IDictionaryRepository
    {
        private IBaseMethod baseMethod;
        public DictionaryRepository(IBaseMethod baseMethod):base(baseMethod)
        {
            this.baseMethod = baseMethod;
        }
        public PageListModel<sys_dictionary> GetLazyNode(decimal? ParentId, int page, int limit)
        {
            Expression<Func<sys_dictionary, bool>> orginExp;
            if (ParentId != null)
            {
                orginExp = t => t.ParentID == ParentId;
            }
            else
            {
                orginExp = t => t.ParentID == null;
            }
            
            var list = baseMethod.Db().Queryable<sys_dictionary>()
                .Where(orginExp)
                .OrderBy(t => t.SortNO)
                .Select(t => new sys_dictionary()
                {
                    ID = t.ID,
                    ParentID = t.ParentID,
                    SortNO = t.SortNO,
                    Name = t.Name,
                    hasChildren = SqlFunc.Subqueryable<sys_dictionary>().Where(a => a.ParentID == t.ID).Any(),     
                })
                .ToPageModel(page, limit);
            return list;
        }
    }
}
